package com.ict.web.service.impl;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ict.common.constant.HttpStatus;
import com.ict.common.core.domain.AjaxResult;
import com.ict.common.core.page.TableDataInfo;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.dto.BaseResponse;
import com.ict.system.dto.FileUploadResp;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.FileService;
import com.ict.web.constant.Constants;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.*;
import com.ict.web.dto.*;
import com.ict.web.mapper.*;
import com.ict.web.msg.domain.SysMsg;
import com.ict.web.msg.mapper.SysMsgMapper;
import com.ict.web.msg.util.CreateMsgUtil;
import com.ict.web.service.*;
import com.ict.web.vo.*;
import io.jsonwebtoken.lang.Collections;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import static com.ict.common.utils.PageUtils.startPage;

/**
 * 年度项目计划Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-14
 */
@Service
public class AnnualProjectPlanServiceImpl extends ServiceImpl<AnnualProjectPlanMapper, AnnualProjectPlan> implements IAnnualProjectPlanService {
    @Resource
    private AnnualProjectPlanMapper annualProjectPlanMapper;

    @Autowired
    private ProjectManagementMapper projectManagementMapper;
    @Autowired
    private IApprovalService approvalService;
    @Autowired
    private IAnnualDeclarationService annualDeclarationService;
    @Autowired
    private IReviewTaskService reviewTaskService;
    @Autowired
    private FileService fileService;
    @Autowired
    private IExtractExpertService extractExpertService;
    @Autowired
    private IYzqFileService yzqFileService;
    @Resource
    private SupplementaryDeclarationMapper supplementaryDeclarationMapper;
    @Resource
    private AnnualDeclarationMapper annualDeclarationMapper;
    @Resource
    private SysMsgMapper sysMsgMapper;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询年度项目计划
     *
     * @param planId 年度项目计划主键
     * @return 年度项目计划
     */
    @Override
    public AnnualProjectPlanDetailsVo selectAnnualProjectPlanByPlanId(Long planId) {
       // System.out.println("详情：" + countProjectValue(planId));
        AnnualProjectPlanDetailsVo annualProjectPlanDetailsVo =
                annualProjectPlanMapper.selectAnnualProjectPlanByPlanId(planId);
        annualProjectPlanDetailsVo.setReviewType(ReviewTask.REVIEW_TYPE_ANNUAL);
        List<ReviewTask> reviewTaskList = reviewTaskService.lambdaQuery().eq(ReviewTask::getPlanId, planId)
                .eq(ReviewTask::getDelFlag, ExtractExpert.DELETE_STATUS_NORMAL).list();
        if (StringUtils.isNotEmpty(reviewTaskList)) {
            annualProjectPlanDetailsVo.setIfExtract("1");
            //返回年度评审任务专家状态
            ReviewTask reviewTask = reviewTaskList.get(0);
            annualProjectPlanDetailsVo.setExpertStatus(reviewTask.getExpertStatus());
            if (StringUtils.isNotNull(reviewTask.getFileId())) {
                List<YzqFile> fileList = yzqFileService.lambdaQuery().eq(YzqFile::getId, reviewTask.getFileId())
                        .eq(YzqFile::getDelFlag, ExtractExpert.DELETE_STATUS_NORMAL).list();
                if (StringUtils.isNotEmpty(fileList)) {
                    annualProjectPlanDetailsVo.setExpertFile(fileList.get(0));
                    annualProjectPlanDetailsVo.setIfExpertFile("1");
                }
            }else {
                annualProjectPlanDetailsVo.setIfExpertFile("0");
            }
        } else {
            annualProjectPlanDetailsVo.setIfExtract("0");
        }
        return annualProjectPlanDetailsVo;
    }

    /**
     * 查询年度项目计划列表
     *
     * @param dto 年度项目计划
     * @return 年度项目计划
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public TableDataInfo selectAnnualProjectPlanList(AnnualProjectPlanListDto dto) {
        List<AnnualProjectPlanListVo> list = annualProjectPlanMapper.selectAnnualProjectPlanList(dto);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        if (CollectionUtil.isNotEmpty(list)) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                AnnualProjectPlanListVo projectPlan = list.get(i);
//                countProjectValue(projectPlan.getPlanId());
                AnnualProjectPlan plan = new AnnualProjectPlan();
                BeanUtils.copyProperties(projectPlan, plan);
                LambdaQueryWrapper<ProjectManagement> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ProjectManagement::getPlanId, plan.getPlanId());
                queryWrapper.eq(ProjectManagement::getIsDelete, 0);
                List<ProjectManagement> projectManagementList = projectManagementMapper.selectList(queryWrapper);
                List<ProjectManagement> collect = projectManagementList.stream()
                        .filter(projectManagement -> projectManagement.getIsState().equals("2"))
                        .collect(Collectors.toList());

                if (LocalDateTime.now().isBefore(projectPlan.getStartTime())) {
                    //当前时间 在 开始时间 之前 状态变为 未启动
                    projectPlan.setIsState(Constants.ANNUAL_PROJECT_PLAN_NOT_STARTED);
                } else if (LocalDateTime.now().isAfter(projectPlan.getStartTime())
                        && LocalDateTime.now().isBefore(projectPlan.getEndTime())
                        && !Constants.ANNUAL_PROJECT_PLAN_PAUSED.equals(projectPlan.getIsState())) {
                    long count = list.stream().limit(i + 1).filter(a ->
                            StringUtils.equals(Constants.ANNUAL_PROJECT_PLAN_REPORTING, a.getIsState())).count();
                    //当前时间 在 开始时间 之后 截止时间 之前 并且状态非暂停 状态变为 正在申报
                    if (count < 1) {
                        projectPlan.setIsState(Constants.ANNUAL_PROJECT_PLAN_REPORTING);
                    }
                } else if (LocalDateTime.now().isAfter(projectPlan.getEndTime())
                ) {
                    //当前时间 在 截至时间 之后 状态变为 待审核
                    projectPlan.setIsState(Constants.ANNUAL_PROJECT_PLAN_TO_BE_REVIEWED);
                }
                List<ProjectManagement> collect1 = projectManagementList.stream()
                        .filter(projectManagement -> Integer.parseInt(projectManagement.getIsState()) >= 2 && Integer.parseInt(projectManagement.getIsState()) !=53)
                        .collect(Collectors.toList());
                if (collect1.size() == projectManagementList.size() && projectManagementList.size() != 0) {
                    //年度计划的所有项目全部审核完毕 状态变为 已审核
                    projectPlan.setIsState(Constants.ANNUAL_PROJECT_PLAN_APPROVED);
                }
            }
            //是否有已启动/正在申报的
            AtomicBoolean hasRunning = new AtomicBoolean(false);
            list = list.stream().map(a -> {
                if (StringUtils.equals(Constants.ANNUAL_PROJECT_PLAN_REPORTING, a.getIsState())) {
                    if (!hasRunning.get()) {
                        hasRunning.set(true);
                    } else if (hasRunning.get()) {
                        a.setIsState(Constants.ANNUAL_PROJECT_PLAN_NOT_STARTED);
                    }
                }
                return a;
            }).collect(Collectors.toList());
        }
        rspData.setRows(list);
        return rspData;
    }

    public int countProjectValue(Long planId) {
        AnnualProjectPlan bean = annualProjectPlanMapper.selectById(planId);
        //查询出 该年度计划下的 项目
        LambdaQueryWrapper<ProjectManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectManagement::getPlanId, planId);
        queryWrapper.eq(ProjectManagement::getIsDelete, 0);
        List<ProjectManagement> list = projectManagementMapper.selectList(queryWrapper);
        bean.setTotalInvestmentEstimation(new BigDecimal("0"));
        bean.setNumberItems(0L);
        for (ProjectManagement projectManagement : list) {
            //设置总的估算
            bean.setTotalInvestmentEstimation(projectManagement.getInvestmentEstimation().add(bean.getTotalInvestmentEstimation()).setScale(6, BigDecimal.ROUND_HALF_UP));
            //设置 项目数量
            bean.setNumberItems(bean.getNumberItems() + 1);
        }
        //设置 项目单位数量
        ArrayList<ProjectManagement> collect1 =
                list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                        -> new TreeSet<>(Comparator.comparing(ProjectManagement::getCompany))), ArrayList::new));
        bean.setNumberProjectUnits(Long.valueOf(collect1.size()));
        //设置 建设类项目 数量
        bean.setConstructionProjects(projectManagementMapper.type(planId, Arrays.asList("0","1")));
        //设置 购买类项目 数量
        bean.setPurchaseItems(projectManagementMapper.type(planId, Arrays.asList("2")));
        //设置 运维项目 数量
        bean.setOperationMaintenance(projectManagementMapper.type(planId, Arrays.asList("3")));
        //设置 其他 数量
        bean.setOther(projectManagementMapper.type(planId, Arrays.asList("4")));
        return annualProjectPlanMapper.updateById(bean);
    }

    /**
     * 查询年度计划对应的项目
     *
     * @param planId 年度项目计划
     * @return 结果
     */
    @Override
    public List<ProjectManagementListVo> selectPlanNumber(Long planId) {
        LambdaQueryWrapper<ProjectManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectManagement::getPlanId, planId);
        queryWrapper.eq(ProjectManagement::getIsDelete, 0);
        queryWrapper.notIn(ProjectManagement::getIsState, "-1");
        queryWrapper.orderByDesc(ProjectManagement::getCreateTime);
        List<ProjectManagement> list = projectManagementMapper.selectList(queryWrapper);
        List<ProjectManagementListVo> voList = new ArrayList<>();
        list.stream().forEach(s -> {
            Approval approval = approvalService.plan(s.getProId());
            ProjectManagementListVo ProjectManagementListVo = new ProjectManagementListVo();
            BeanUtils.copyProperties(s, ProjectManagementListVo);
            if (StringUtils.isNotNull(approval)) {
                ProjectManagementListVo.setApprovalStatus(approval.getApprovalStatus());
                ProjectManagementListVo.setApprovalStatusName(ProjectStatusEnum.getEnum(approval.getApprovalStatus()).getStatusDes());
            }
            ProjectManagementListVo.setAnnualId(s.getAnnualId());
            voList.add(ProjectManagementListVo);
        });
        return voList;
    }

    /**
     * 查询年度计划对应的项目(分页)
     *
     * @param selectPlanDto 年度项目计划
     * @return 结果
     */
    @Override
    public PageInfo<ProjectManagementListVo> selectPlanNumberPage(SelectPlanDto selectPlanDto) {

        List<ProjectManagementListVo> list =
                projectManagementMapper.selectProjectManagementListVo(selectPlanDto.getPlanId(),
                        new RowBounds(selectPlanDto.getPageNum(), selectPlanDto.getPageSize()));
        list.stream().forEach(s -> {
            Approval approval = approvalService.plan(s.getProId());
            if (StringUtils.isNotNull(approval)) {
                s.setApprovalStatus(approval.getApprovalStatus());
                s.setApprovalStatusName(ProjectStatusEnum.getEnum(approval.getApprovalStatus()).getStatusDes());
            }
        });
        return new PageInfo<>(list);
    }

    /**
     * 新增年度项目计划
     *
     * @param dto 年度项目计划
     * @return 结果
     */
    @Override
    public Long insertAnnualProjectPlan(AnnualProjectPlanAddDto dto) {
        //年度计划名称校验
        QueryWrapper<AnnualProjectPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", dto.getName());
        queryWrapper.eq("is_delete", Constants.DELETE_STATUS_NORMAL);
        List<AnnualProjectPlan> list = annualProjectPlanMapper.selectList(queryWrapper);
        Assert.isTrue(Collections.isEmpty(list), "年度项目计划名称重复");
        //检查时间是否冲突
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(dto.getStartTime());
        String endTime = df.format(dto.getEndTime());
        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + startTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + startTime + "')");
        List<AnnualProjectPlan> annualProjectPlans1 = annualProjectPlanMapper.selectList(lambdaQueryWrapper1);

        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + endTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + endTime + "')");
        List<AnnualProjectPlan> annualProjectPlans2 = annualProjectPlanMapper.selectList(lambdaQueryWrapper2);

        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + startTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + endTime + "')");
        List<AnnualProjectPlan> annualProjectPlans3 = annualProjectPlanMapper.selectList(lambdaQueryWrapper3);
        Assert.isTrue(annualProjectPlans1.isEmpty() && annualProjectPlans2.isEmpty() && annualProjectPlans3.isEmpty()
                , "当前已有正在申报的年度计划，请重新选择时间");

        AnnualProjectPlan bean = AnnualProjectPlanAddDto.of(dto);

        //启动时间为当前，直接变为正在申报
        if (LocalDateTime.now().compareTo(dto.getStartTime())>=0) {
            bean.setIsState(Constants.ANNUAL_PROJECT_PLAN_REPORTING);
            List<Long> userIds = sysUserRoleMapper.getUserIdByRoleId(102L);
            for (Long userId:userIds){
                CreateMsgUtil.createMsgAnnualProjectPlan(CreateMsgUtil.ANNUAL_PLAN_TO_DO, userId, null,
                        CreateMsgUtil.ANNUAL_PLAN_TO_DO, SysMsg.RESOURCE_TYPE_UNIT,null,bean.getPlanId());
            }
        }
        annualProjectPlanMapper.insert(bean);
        return bean.getPlanId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStag(Long planId) {
        AnnualProjectPlan bean = annualProjectPlanMapper.selectById(planId);
        bean.setUpdateTime(LocalDateTime.now());
        Assert.isTrue(LocalDateTime.now().isAfter(bean.getStartTime()) && LocalDateTime.now().isBefore(bean.getEndTime()), "非申报阶段，无法变更");

        if (bean.getIsState().equals(Constants.ANNUAL_PROJECT_PLAN_REPORTING)) {
            //正在申报，变为 暂停
            bean.setIsState(Constants.ANNUAL_PROJECT_PLAN_PAUSED);
            //修改消息可见
            updateMsgStatus(bean,"0","1");
        } else if (bean.getIsState().equals(Constants.ANNUAL_PROJECT_PLAN_PAUSED)) {
            //只允许出现一个正在申报的项目
            LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AnnualProjectPlan::getIsState, Constants.ANNUAL_PROJECT_PLAN_REPORTING);
            lambdaQueryWrapper.eq(AnnualProjectPlan::getIsDelete, 0);
            Integer count = annualProjectPlanMapper.selectCount(lambdaQueryWrapper);
            Assert.isTrue(count == 0, "已有正在申报的年度计划，无法启动");
            //暂停，变为 正在申报
            bean.setIsState(Constants.ANNUAL_PROJECT_PLAN_REPORTING);
            //修改消息可见
            updateMsgStatus(bean,"1","0");
        }
        return annualProjectPlanMapper.updateById(bean);
    }

    /**
     * 修改年度项目计划
     *
     * @param planId 年度项目计划
     * @return 结果
     */
    @Override
    public int updateAnnualProjectPlan(AnnualProjectPlanEditDto dto, Long planId) {
        AnnualProjectPlan bean = annualProjectPlanMapper.selectById(planId);
        Assert.isTrue(StringUtils.isNotNull(bean), "该年度项目计划不存在");
        if (!dto.getName().equals(bean.getName())) {
            QueryWrapper<AnnualProjectPlan> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", dto.getName());
            queryWrapper.eq("is_delete", Constants.DELETE_STATUS_NORMAL);
            List<AnnualProjectPlan> list = annualProjectPlanMapper.selectList(queryWrapper);
            Assert.isTrue(Collections.isEmpty(list), "年度项目计划名称重复");
        }
        //禁止将已进入申报进程的计划重置为未启动
        if (bean.getIsState().equals(Constants.ANNUAL_PROJECT_PLAN_PAUSED)) {
            Assert.isTrue(LocalDateTime.now().compareTo(dto.getStartTime()) > 0,"禁止将已进入申报进程的计划重置!");
        }
        //检查时间是否冲突
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(dto.getStartTime());
        String endTime = df.format(dto.getEndTime());
        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + startTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + startTime + "')");
        List<AnnualProjectPlan> annualProjectPlans1 = annualProjectPlanMapper.selectList(lambdaQueryWrapper1);

        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + endTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + endTime + "')");
        List<AnnualProjectPlan> annualProjectPlans2 = annualProjectPlanMapper.selectList(lambdaQueryWrapper2);

        LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .eq(AnnualProjectPlan::getIsState, "44")
                .apply("UNIX_TIMESTAMP(start_time) <= UNIX_TIMESTAMP('" + startTime + "')")
                .apply("UNIX_TIMESTAMP(end_time) >= UNIX_TIMESTAMP('" + endTime + "')");
        List<AnnualProjectPlan> annualProjectPlans3 = annualProjectPlanMapper.selectList(lambdaQueryWrapper3);
        Assert.isTrue(annualProjectPlans1.isEmpty() && annualProjectPlans2.isEmpty() && annualProjectPlans3.isEmpty()
                , "当前已有正在申报的年度计划，请重新选择时间");
        BeanUtils.copyProperties(dto, bean);
        bean.setUpdateTime(LocalDateTime.now());

        //启动时间为当前，直接变为正在申报
        if (LocalDateTime.now().compareTo(dto.getStartTime())>=0) {
            bean.setIsState(Constants.ANNUAL_PROJECT_PLAN_REPORTING);
            List<Long> userIds = sysUserRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_PROJECT);
            for (Long userId:userIds){
                CreateMsgUtil.createMsgAnnualProjectPlan(CreateMsgUtil.ANNUAL_PLAN_TO_DO, userId, null,
                        CreateMsgUtil.ANNUAL_PLAN_TO_DO, SysMsg.RESOURCE_TYPE_UNIT,null,bean.getPlanId());
            }
        }
        return annualProjectPlanMapper.updateById(bean);
    }

    /**
     * 删除年度项目计划信息
     *
     * @param planId 年度项目计划主键
     * @return 结果
     */
    @Override
    public int deleteAnnualProjectPlanByPlanId(Long planId) {
        AnnualProjectPlan bean = annualProjectPlanMapper.selectById(planId);
        bean.setIsDelete("1");
        return annualProjectPlanMapper.updateById(bean);
    }

    @Override
    public AnnualProjectPlan ifAnnualProject() {
        QueryWrapper<AnnualProjectPlan> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
//        queryWrapper.eq("year", LocalDateTime.now().getYear());
        queryWrapper.le(true, "start_time", now);
        queryWrapper.gt(true, "end_time", now);
        queryWrapper.eq("is_delete", ExtractExpert.DELETE_STATUS_NORMAL);
        queryWrapper.eq("is_state", Constants.ANNUAL_PROJECT_PLAN_REPORTING);
        //测试数据没有唯一处在正在申报状态的数据，暂时改为取列表第一条
//        AnnualProjectPlan annualProjectPlan = annualProjectPlanMapper.selectOne(queryWrapper);
//        if (StringUtils.isNull(annualProjectPlan)) {
//            return null;
//        }
//        return annualProjectPlan.getName();

        List<AnnualProjectPlan> annualProjectPlans = annualProjectPlanMapper.selectList(queryWrapper);
        if (annualProjectPlans.isEmpty()) {
            return null;
        }
        return annualProjectPlans.get(0);
    }

    @Override
    public List<YearVo> getYear() {
        List<YearVo> list = new ArrayList<>();
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear()), LocalDateTime.now().getYear()));
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear() + 1), (LocalDateTime.now().getYear()) + 1));
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear() + 2), (LocalDateTime.now().getYear()) + 2));
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear() + 3), (LocalDateTime.now().getYear()) + 3));
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear() + 4), (LocalDateTime.now().getYear()) + 4));
        list.add(new YearVo(String.valueOf(LocalDateTime.now().getYear() + 5), (LocalDateTime.now().getYear()) + 5));
        return list;
    }

    @Override
    public List<AnnualProjectPlan> getTimeList() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<AnnualProjectPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(AnnualProjectPlan::getStartTime, now)
                .eq(AnnualProjectPlan::getIsDelete, "0")
                .select(AnnualProjectPlan::getStartTime, AnnualProjectPlan::getEndTime);
        return annualProjectPlanMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult upload(YzqFile file, Long planId) {
        AnnualProjectPlan projectPlan = annualProjectPlanMapper.selectById(planId);
        Assert.isTrue(StringUtils.isNotNull(projectPlan), "未找到该年度计划");
        //更新年度计划抽取出来的专家状态、抽取表状态、评审任务，为现场论证已结束，
        List<ReviewTask> reviewTaskList =
                reviewTaskService.lambdaQuery().eq(ReviewTask::getPlanId, planId).eq(ReviewTask::getDelFlag,
                        ExtractExpert.DELETE_STATUS_NORMAL).list();
        Assert.isTrue(StringUtils.isNotEmpty(reviewTaskList), "未找到该年度计划对应的评审任务");
        ReviewTask reviewTask = reviewTaskList.get(0);
        reviewTask.setExpertStatus(ReviewTask.EXTRACT_STATUS_NOT_EVALUATE);
        reviewTask.setNodeStatus(ProjectStatusEnum.THE_ONSITE_DEMONSTRATION_HAS_BEEN_PASSED.get().getStatus());
        reviewTask.setNode(ProjectStatusEnum.THE_ONSITE_DEMONSTRATION_HAS_BEEN_PASSED.get().getNode());

        //抽取表状态
        List<ExtractExpert> extractExpertList = reviewTaskService.getExtractExpertList(reviewTask.getReviewTaskId());
        Assert.isTrue(StringUtils.isNotEmpty(extractExpertList), "未找到该年度计划抽取的专家");
        //专家抽取表状态都为已接受时才能导入专家审核结论
        List<ExtractExpert> collect =
                extractExpertList.stream().filter(s -> s.getReceiveStatus().equals(ExtractExpert.RECEIVE_STATUS_ACCEPT)).collect(Collectors.toList());
        if (collect.size() != extractExpertList.size()) {
            return   AjaxResult.error().put("code","500").put("msg","专家未接受任务，无法上传审核结果");
        };

        List<ExtractExpert> list = new ArrayList<>();
        extractExpertList.stream().forEach(s -> {
            ExtractExpert expert = new ExtractExpert();
            BeanUtils.copyProperties(s, expert);
            expert.setStatus(ExtractExpert.STATUS_FINISH);
            expert.setExtractNode(ProjectStatusEnum.THE_ONSITE_DEMONSTRATION_HAS_BEEN_PASSED.get().getStatus());
            list.add(expert);
        });
        extractExpertService.saveOrUpdateBatch(list);
        List<Approval> approvalList = approvalService.lambdaQuery().eq(Approval::getPlanId, planId)
                .eq(Approval::getApprovalType, Approval.APPROVAL_TYPE_EXPERT)
                .eq(Approval::getApprovalStatus,
                        ProjectStatusEnum.ON_SITE_DEMONSTRATION_TO_BE_REVIEWED.get().getStatus()).list();
        if (StringUtils.isNotEmpty(approvalList)) {
            approvalList.stream().forEach(s -> {
                s.setApprovalStatus(ProjectStatusEnum.THE_ONSITE_DEMONSTRATION_HAS_BEEN_PASSED.get().getStatus());
            });
            approvalService.saveOrUpdateBatch(approvalList);
        }

        YzqFile yzqFile = new YzqFile();
        yzqFile.setId(String.valueOf(IdUtils.snowId()));
        yzqFile.setFileName(file.getFileName());
        yzqFile.setFileUrl(file.getFileUrl());
        yzqFile.setDelFlag(ExtractExpert.DELETE_STATUS_NORMAL);
        yzqFileService.save(yzqFile);
        reviewTask.setFileId(Long.valueOf(yzqFile.getId()));
        reviewTaskService.updateById(reviewTask);
        //年度计划下每个项目的申报审核进程资料库返回专家审核结论
        List<ProjectManagement> projectManagementList = projectManagementMapper.selectList(new QueryWrapper<ProjectManagement>().eq("plan_id", planId));
        projectManagementList.stream().forEach(s->{
            List<Approval> approvals = approvalService.lambdaQuery().eq(Approval::getProjectId, s.getProId())
                    .eq(Approval::getApprovalType, Approval.APPROVAL_TYPE_PROJECT_MANAGE)
                    .eq(Approval::getApprovalNode, ProjectStatusEnum.APPLICATION_REVIEW_PASSED.get().getNode())
                    .orderByAsc(Approval::getCreateTime).list();
            if(StringUtils.isNotEmpty(approvals)){
                Approval approval = approvals.get(0);
                approval.setApprovalDatabase(yzqFile.getId());
                approvalService.updateById(approval);
            }
        });
        return AjaxResult.success().put("code","200").put("data",yzqFile);
    }

    @Override
    public boolean deleteFile(Long fileId) {
        YzqFile yzqFile = yzqFileService.getById(fileId);
        Assert.isTrue(StringUtils.isNotNull(yzqFile), "未找到该文件");
        yzqFile.setDelFlag(ExtractExpert.DELETE_STATUS_DELETED);
        return yzqFileService.updateById(yzqFile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int terminateAnnualPlan(Long planId) {
        AnnualProjectPlan annualProjectPlan = annualProjectPlanMapper.selectById(planId);
        Assert.isTrue(annualProjectPlan.getIsState().equals(ProjectStatusEnum.ANNUAL_PROJECT_PLAN_REPORTING.get().getStatus()),"年度计划不在申报时间，无法终止！");
        annualProjectPlan.setEndTime(LocalDateTime.now());
        annualProjectPlan.setIsState(ProjectStatusEnum.ANNUAL_PROJECT_PLAN_TO_BE_REVIEWED.get().getStatus());
        updateMsgStatus(annualProjectPlan, "0", "1");
        return annualProjectPlanMapper.updateById(annualProjectPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult supplement2year(Long planId,Long proId) {
        ProjectManagement projectManagement = projectManagementMapper.selectById(proId);
        Assert.notNull(projectManagement,"增补项目不存在");
        Assert.isTrue(projectManagement.getIsState().equals("1"),"增补项目不是待审核状态");
        SupplementaryDeclaration supplementaryDeclaration = supplementaryDeclarationMapper.selectSupplementaryDeclarationBySupplementaryId(projectManagement.getSupplementaryId());
        Assert.notNull(supplementaryDeclaration,"增补项目不存在");
        AnnualDeclaration bean = new AnnualDeclaration();
        //设置ID
        BeanUtils.copyProperties(supplementaryDeclaration,bean);
        bean.setWorkCompletion(supplementaryDeclaration.getPreliminaryWorkCompletion());
        bean.setAnnualId(projectManagement.getSupplementaryId());
        AnnualProjectPlan annualProjectPlan = annualProjectPlanMapper.selectById(planId);
        Assert.isTrue(StringUtils.isNotNull(annualProjectPlan),"未找到该年度计划");
        Assert.isTrue(ProjectStatusEnum.ANNUAL_PROJECT_PLAN_TO_BE_REVIEWED.get().getStatus().equals(annualProjectPlan.getIsState()),
                "年度计划必须为待审核状态才能转入");
        bean.setPlanId(planId);
        bean.setPlanName(annualProjectPlan.getName());
        annualDeclarationMapper.insert(bean);
        projectManagement.setAnnualId(projectManagement.getSupplementaryId());
        projectManagement.setSupplementaryId(null);
        projectManagement.setNature("0");
        projectManagement.setPlanId(planId);
        projectManagementMapper.updateById(projectManagement);
        supplementaryDeclaration.setDelFlag(Constants.DELETE_STATUS_DELETED);
        supplementaryDeclarationMapper.updateById(supplementaryDeclaration);
        /*approvalMapper.update( null,new UpdateWrapper<Approval>().lambda().
        set(Approval::getDelFlag,Constants.DELETE_STATUS_DELETED).eq(Approval::getProjectId,proId).eq(Approval::getApprovalStatus,ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus()));*/
        AnnualDeclarationAddDto beanAdd = new AnnualDeclarationAddDto();
        BeanUtils.copyProperties(supplementaryDeclaration,beanAdd);
        //年度计划统计数量更新
        annualDeclarationService.totalProjectNumber(annualProjectPlan,beanAdd);
        return AjaxResult.success();
    }

    @Override
    public int batchUpdate(List<AnnualProjectPlan> list) {
        return annualProjectPlanMapper.batchUpdate(list);
    }

    private void updateMsgStatus(AnnualProjectPlan plan, String getStatus, String setStatus){
        //修改消息可见
        LambdaQueryWrapper<SysMsg> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SysMsg::getPlanId,plan.getPlanId())
                .eq(SysMsg::getMsgStatus,getStatus);
        List<SysMsg> sysMsgs = sysMsgMapper.selectList(queryWrapper1);
        if (StringUtils.isNotNull(sysMsgs)) {
            sysMsgs.forEach(s->{
                s.setMsgStatus(setStatus);
                sysMsgMapper.updateById(s);
            });
        }
    }
}
